<template>
  <div class="login-container">
    <img class="login-bg" src="http://yd.sjcmc.cn:16578/wp-content/uploads/2025/01/login-bg3-scaled.jpg" />
    <h1 class="auth-title">XIN计划</h1>
    <van-tabs
      class="tab-switcher-tab"
      :show-header="false"
      animated
      swipeable
      @change="onTabChange"
      v-model:active="tabActive"
    >
      <van-tab key="login">
        <div class="van-tabs-item">
          <LoginForm :tabActive="tabActive" />
        </div>
      </van-tab>
      <van-tab key="register">
        <div class="van-tabs-item">
          <RegisterForm :tabActive="tabActive" />
        </div>
      </van-tab>
    </van-tabs>
    <van-floating-bubble icon="chat" @click="onClickFloating" />
  </div>
</template>

<script setup>
// 公告组件
// import Announcement from "./Announcement.vue";
import { showDialog } from 'vant'
import _ from 'lodash-es'
import { ElMessage } from 'element-plus'
import LoginForm from './loginForm.vue'
import RegisterForm from './registerForm.vue'
import { ref, reactive, onMounted } from 'vue'
import { sendCaptcha, updatePassword } from '@/api/user'

// 初始化提示
const initTitle = () => {
  const isInit = !window.localStorage.getItem('isInit')
  if (isInit) {
    showDialog({
      message: '嗨小XIN，如果还没通行证，左滑可前往注册账号哦!'
    })
    window.localStorage.setItem('isInit', '1')
  }
}
// 点击登录/注册按钮
const tabActive = reactive({
  active: 0
})

// 在组件挂载时检查本地存储
onMounted(() => {
  initTitle()
})

// 切换登录/注册模式
const onTabChange = (tab) => {
  tabActive.active = tab
}

// 忘记密码相关
const showForgotPasswordDialog = ref(false)
const forgotPasswordFormRef = ref(null)
const resetLoading = ref(false)
const resetCountdown = ref(0)
const canSendResetCode = ref(true)

const forgotPasswordForm = reactive({
  email: '',
  captcha: '',
  newPassword: ''
})

const forgotPasswordRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]{6}$/, message: '验证码必须是6位字母或数字', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
}

// 发送重置密码验证码的核心逻辑
const sendResetCodeCore = async () => {
  if (!forgotPasswordForm.email) {
    ElMessage.error('请先输入邮箱')
    return
  }

  if (resetCountdown.value > 0) {
    return
  }

  canSendResetCode.value = false
  resetCountdown.value = 60

  const timer = setInterval(() => {
    resetCountdown.value--
    if (resetCountdown.value <= 0) {
      canSendResetCode.value = true
      clearInterval(timer)
    }
  }, 1000)

  try {
    const json = {
      email: forgotPasswordForm.email,
      scene: 'update'
    }
    const res = await sendCaptcha(json)
    if (res.code === 200) {
      ElMessage.success('验证码已发送，请查收邮件')
    } else {
      ElMessage.error(res.msg || '发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error('发送失败，请稍后重试')
  }
}

// 使用防抖包装的发送重置验证码函数
const sendResetCode = _.debounce(sendResetCodeCore, 300)

// 重置密码
const handleResetPassword = async () => {
  if (!forgotPasswordFormRef.value) return

  await forgotPasswordFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      resetLoading.value = true
      try {
        const json = {
          email: forgotPasswordForm.email,
          captcha: forgotPasswordForm.captcha,
          password: forgotPasswordForm.newPassword
        }
        const res = await updatePassword(json)
        if (res.code === 200) {
          ElMessage.success('密码重置成功，请使用新密码登录')
          showForgotPasswordDialog.value = false
          // 重置表单
          forgotPasswordForm.email = ''
          forgotPasswordForm.captcha = ''
          forgotPasswordForm.newPassword = ''
        } else {
          ElMessage.error(res.msg || '重置失败')
        }
      } catch (error) {
        console.error('重置密码失败:', error)
        ElMessage.error('重置失败')
      } finally {
        resetLoading.value = false
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  width: 100%;
  overflow: hidden;

  .login-bg {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    object-fit: cover;
    filter: blur(5px);
    z-index: 0;
  }
  .auth-title {
    padding-left: 30px;
    width: 100%;
    height: 150px;
    top: 10px;
    position: absolute;
    font-size: 24px;
    font-weight: 700;
    color: #333;
    margin: 0;
    line-height: 100px;
    z-index: 1;
    letter-spacing: 2px;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  }

  .tab-switcher-tab {
    width: 100%;
    height: 50%;
    .van-tabs-item {
      width: 100%;
      height: calc(100vh - 150px);
      padding-top: 16px;
    }
  }
}

// 自定义滚动条样式
:deep(.el-scrollbar__bar) {
  &.is-horizontal {
    display: none;
  }

  &.is-vertical {
    width: 6px;

    .el-scrollbar__thumb {
      background-color: rgba(144, 147, 153, 0.3);

      &:hover {
        background-color: rgba(144, 147, 153, 0.5);
      }
    }
  }
}

// 添加动画关键帧
@keyframes bounce {
  0%,
  100% {
    transform: translateY(0) scale(1);
  }
  50% {
    transform: translateY(-15px) scale(1.05);
  }
}

// 添加动画
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
